//
//  UIImage+GL.m
//  GLLibDemo
//
//  Created by huanggulong on 2017/4/19.
//  Copyright © 2017年 历山大亚. All rights reserved.
//

#import "UIImage+GL.h"

@implementation UIImage (GL)

#pragma mark - instance method
- (UIImage *)gl_thumbImageWithSize:(CGSize)size{
    if (size.height == 0 || size.width == 0) {
        return nil;
    }
    UIGraphicsBeginImageContext(size);
    
    CGFloat scale1 = size.width / size.height;
    CGFloat scale2 = self.size.width / self.size.height;
    if (scale2 > scale1) {
        CGFloat tempWidth = self.size.width *size.height / self.size.height;
        [self drawInRect:CGRectMake((size.width - tempWidth) * 0.5, 0, tempWidth, size.height)];
    }else{
        CGFloat tempHeight = self.size.height *size.width / self.size.width;
        [self drawInRect:CGRectMake(0, (size.height - tempHeight) , size.width, tempHeight)];
        
    }
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage *)gl_thumbImageWithSideLength:(CGFloat)sideLength{
    return [self gl_thumbImageWithSize:CGSizeMake(sideLength, sideLength)];
}


+ (UIImage *)gl_imageWithColor:(UIColor *)color size:(CGSize)size{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}




- (UIImage *)gl_scaleImageWithMinLength:(CGFloat)length{
    CGSize size = self.size;
    if (size.width < size.height) { //e.g   1200 x 3000  -->  300 x 750
        size = CGSizeMake(length, size.height * length / size.width);
    }else if(size.width == size.height){ //e.g   1200 x 1200  -->  300 x 300
        size = CGSizeMake(length, length);
    }else{  //e.g   3000 x 1200  -->  750 x 300
        size = CGSizeMake( size.width * length / size.height,length);
    }
    
    UIGraphicsBeginImageContext(size);
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    
}

- (UIImage *)gl_scaleImageWithMaxLength:(CGFloat)length{
    CGSize size = self.size;
    if (size.width > size.height) { //e.g   1200 x 200  -->  300 x 50
        size = CGSizeMake(length, size.height * length / size.width);
    }else if(size.width == size.height){ //e.g   1200 x 1200  -->  300 x 300
        size = CGSizeMake(length, length);
    }else{  //e.g   200 x 1200  -->  50 x 300
        size = CGSizeMake( size.width * length / size.height,length);
    }
    
    UIGraphicsBeginImageContext(size);
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    
}

- (UIColor *)mainColorDeleteWhite:(BOOL)deleteWhite{
    UIImage *image = self;
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    //第一步 先把图片缩小 加快计算速度. 但越小结果误差可能越大
    CGSize thumbSize=CGSizeMake(image.size.width/2, image.size.height/2);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 bitmapInfo);
    
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);
    
    //第二步 取每个点的像素值
    unsigned char* data = CGBitmapContextGetData (context);
    if (data == NULL) return nil;
    NSCountedSet *cls=[NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
    
    for (int x=0; x<thumbSize.width; x++) {
        for (int y=0; y<thumbSize.height; y++) {
            int offset = 4*(x*y);
            int red = data[offset];
            int green = data[offset+1];
            int blue = data[offset+2];
            int alpha =  data[offset+3];
            if (alpha>0) {//去除透明
                if (red==255&&green==255&&blue==255) {//去除白色
                    if (!deleteWhite) {
                        NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
                        [cls addObject:clr];
                    }
                }else{
                    NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
                    [cls addObject:clr];
                }
                
            }
        }
    }
    CGContextRelease(context);
    //第三步 找到出现次数最多的那个颜色
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *curColor = nil;
    NSArray *MaxColor=nil;
    NSUInteger MaxCount=0;
    while ( (curColor = [enumerator nextObject]) != nil )
    {
        NSUInteger tmpCount = [cls countForObject:curColor];
        if ( tmpCount < MaxCount ) continue;
        MaxCount=tmpCount;
        MaxColor=curColor;
        
    }
    return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f) green:([MaxColor[1] intValue]/255.0f) blue:([MaxColor[2] intValue]/255.0f) alpha:([MaxColor[3] intValue]/255.0f)];
}


- (UIImage *)gl_fixOrientation{
    UIImage *aImage = self;
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

#pragma mark - class method

+ (UIImage *)gl_centerRoundRadius:(CGFloat)radius size:(CGSize)size color:(UIColor *)color{
    UIGraphicsBeginImageContextWithOptions(size, 0, [UIScreen mainScreen].scale);
    
    CGFloat centerX = size.width * 0.5;
    CGFloat centerY = size.height * 0.5;
    CGFloat bRadius = centerX > centerY ? centerY : centerX;//大圆半径
    
    //获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(ctx, 0);
    //外部大圆
    CGContextSetFillColorWithColor(ctx, [[UIColor whiteColor] colorWithAlphaComponent:0.8].CGColor);
    CGContextAddArc(ctx, centerX, centerY, bRadius, 0, 2*M_PI, 0);
    //    CGContextFillRect(ctx, CGRectMake(0, 0, 16, 16));
    CGContextDrawPath(ctx, kCGPathFillStroke);
    
    //内部小圆
    CGContextSetFillColorWithColor(ctx, color.CGColor);
    CGContextAddArc(ctx, centerX, centerY, radius, 0, 2*M_PI, 0);
    //    CGContextFillRect(ctx, CGRectMake(0, 0, 16, 16));
    CGContextDrawPath(ctx, kCGPathFillStroke);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}


+ (UIImage *)gl_currentScreenImage{
    CGSize imageSize = CGSizeZero;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation))
        imageSize = [UIScreen mainScreen].bounds.size;
    else
        imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow *window in [[UIApplication sharedApplication] windows])
    {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
        if (orientation == UIInterfaceOrientationLandscapeLeft)
        {
            CGContextRotateCTM(context, M_PI_2);
            CGContextTranslateCTM(context, 0, -imageSize.width);
        }
        else if (orientation == UIInterfaceOrientationLandscapeRight)
        {
            CGContextRotateCTM(context, -M_PI_2);
            CGContextTranslateCTM(context, -imageSize.height, 0);
        } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
            CGContextRotateCTM(context, M_PI);
            CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
        }
        if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
        {
            [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
        }
        else
        {
            [window.layer renderInContext:context];
        }
        CGContextRestoreGState(context);
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

/*
 * @huanggulong
 *
 * 通过颜色生成一个村色的图片9(大小 1 x 1)
 */
+ (UIImage *)gl_imageWithColor:(UIColor *)color{
    return [self gl_imageWithColor:color size:CGSizeMake(1, 1)];
}

/*
 * @huanggulong
 *
 * 获取一个纯色的圆
 *
 */
+(UIImage *)gl_badgeImageWithColor:(UIColor *)color withSize:(CGSize)size{
    //    //新建一个图片图形上下文
    CGFloat radius = size.width >= size.height ? (size.width  * 0.5) : (size.height * 0.5);
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    //    UIGraphicsBeginImageContext(size);
    //获取上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(ctx, color.CGColor);
    CGContextAddArc(ctx, size.width * 0.5, size.height * 0.5, radius, 0, 2*M_PI, 0);
    CGContextDrawPath(ctx,kCGPathFill);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}


+(instancetype)drawGradientImageWithSize:(CGSize)size beginColor:(UIColor *)beginColor endColor:(UIColor *)endColor isVertical:(BOOL)v{
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef beginColorRef = CGColorCreateCopy([beginColor CGColor]);
    CGColorRef endColorRef = CGColorCreateCopy([endColor CGColor]);
    CFArrayRef colorArray = CFArrayCreate(kCFAllocatorDefault, (const void*[]){beginColorRef,endColorRef}, 2, nil);
    CGGradientRef gradientRef = CGGradientCreateWithColors(colorSpace, colorArray, (CGFloat[]){0.0,1.0});
    CFRelease(colorArray);
//    CGColorRelease(beginColorRef);
//    CGColorRelease(endColorRef);
    CGColorSpaceRelease(colorSpace);
    if (v) {
        CGContextDrawLinearGradient(context, gradientRef, CGPointMake(0, 0),  CGPointMake(0, size.height), 0);
    }else{
        CGContextDrawLinearGradient(context, gradientRef, CGPointZero, CGPointMake(size.width, 0), 0);
    }
    CGGradientRelease(gradientRef);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


#pragma mark - global method
UIImage * drawGradientImageWithSize(CGSize size ,UIColor *beginColor, UIColor *endColor , bool v ){
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef beginColorRef = beginColor.CGColor;
    CGColorRef endColorRef = endColor.CGColor;
    CFArrayRef colorArray = CFArrayCreate(kCFAllocatorDefault, (const void*[]){beginColorRef,endColorRef}, 2, nil);
    CGGradientRef gradientRef = CGGradientCreateWithColors(colorSpace, colorArray, (CGFloat[]){0.0,1.0});
    CFRelease(colorArray);
    CGColorRelease(beginColorRef);
    CGColorRelease(endColorRef);
    CGColorSpaceRelease(colorSpace);
    if (v) {
        CGContextDrawLinearGradient(context, gradientRef, CGPointMake(0, 0),  CGPointMake(0, size.height), 0);
    }else{
        CGContextDrawLinearGradient(context, gradientRef, CGPointZero, CGPointMake(size.width, 0), 0);
    }
    CGGradientRelease(gradientRef);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}



UIImage * screenshot2(UIView *view){
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


@end
